package com.dces.jx.billtest.zhj.service;

import com.dces.jx.billtest.userAdd.dao.DcBillListZhjMapper;
import com.dces.jx.billtest.zhj.model.Recovery;
import com.dces.jx.billtest.zhj.model.StatusInfo;
import com.dces.jx.billtest.zhj.model.Task;
import com.xdo.domain.PageParam;
import com.dces.jx.billtest.dto.zhj.*;
import com.xdo.common.token.UserInfoToken;
import com.xdo.domain.ResultObject;
import com.xdo.common.base.service.BaseService;
import com.dces.jx.billtest.zhj.dao.DcBillHeadZhjMapper;
import com.dces.jx.billtest.zhj.mapper.DcBillHeadZhjDtoMapper;
import com.dces.jx.billtest.zhj.model.DcBillHeadZhj;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import javax.annotation.Resource;
import java.beans.Transient;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * generated by Generate 神码
 * Service;
 *
 * @author xdoV2.0
 * @date: 2021-9-3
 */
@Service
public class DcBillHeadZhjService extends BaseService<DcBillHeadZhj> {
    @Resource
    private DcBillHeadZhjMapper dcBillHeadZhjMapper;
    @Resource
    private DcBillHeadZhjDtoMapper dcBillHeadZhjDtoMapper;
    @Resource
    private DcBillListZhjMapper dcBillListZhjMapper;

    @Override
    public Mapper<DcBillHeadZhj> getMapper() {
        return dcBillHeadZhjMapper;
    }
    // 申报状态3
    public static final String DECLARE_TYPE_THREE ="3";
    // 申报状态6
    public static final String DECLARE_TYPE_SIX ="6";
    // 状态
    public static final String STATUS = "edit";
    public static final String TRADE_MODE_0644 ="0644";
    public static final String TRADE_MODE_0245 ="0245";
    public static final String TRADE_MODE_0844 ="0844";
    public static final String TRADE_MODE_0845 ="0845";


    /**
     * 获取分页信息
     *
     * @param dcBillHeadZhjParam
     * @param pageParam
     * @return
     * @author zuzhu
     */
    public ResultObject<List<DcBillHeadZhjDto>> getListPaged(DcBillHeadZhjParam dcBillHeadZhjParam, PageParam pageParam) {
        // 启用分页查询
        DcBillHeadZhj dcBillHeadZhj = dcBillHeadZhjDtoMapper.toPo(dcBillHeadZhjParam);
        Page<DcBillHeadZhj> page = PageHelper.startPage(pageParam.getPage(), pageParam.getLimit(), pageParam.getSortOrderContent())
                .doSelectPage(() -> dcBillHeadZhjMapper.getList(dcBillHeadZhj));
        List<DcBillHeadZhjDto> dcBillHeadZhjDtos = page.getResult().stream().map(head -> {
            DcBillHeadZhjDto dto = dcBillHeadZhjDtoMapper.toDto(head);
            return dto;
        }).collect(Collectors.toList());
        ResultObject<List<DcBillHeadZhjDto>> paged = ResultObject.createInstance(dcBillHeadZhjDtos, (int) page.getTotal(), page.getPageNum());
        return paged;
    }

    /**
     * 功能描述:新增
     *
     * @param dcBillHeadZhjParam
     * @param userInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DcBillHeadZhjDto insert(DcBillHeadZhjParam dcBillHeadZhjParam, UserInfoToken userInfo) {
        DcBillHeadZhj dcBillHeadZhj = dcBillHeadZhjDtoMapper.toPo(dcBillHeadZhjParam);
        /**
         * 规范固定字段
         */
        String sid = UUID.randomUUID().toString();
        dcBillHeadZhj.setSid(sid);
        dcBillHeadZhj.setInsertUser(userInfo.getUserNo());
        dcBillHeadZhj.setInsertTime(new Date());
        // 新增数据
        int insertStatus = dcBillHeadZhjMapper.insert(dcBillHeadZhj);
        return insertStatus > 0 ? dcBillHeadZhjDtoMapper.toDto(dcBillHeadZhj) : null;
    }

    /**
     * 功能描述:修改
     *
     * @param dcBillHeadZhjParam
     * @param userInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DcBillHeadZhjDto update(DcBillHeadZhjParam dcBillHeadZhjParam, UserInfoToken userInfo) {
        DcBillHeadZhj dcBillHeadZhj = dcBillHeadZhjMapper.selectByPrimaryKey(dcBillHeadZhjParam.getSid());
        dcBillHeadZhjDtoMapper.updatePo(dcBillHeadZhjParam, dcBillHeadZhj);
        dcBillHeadZhj.setUpdateUser(userInfo.getUserNo());
        dcBillHeadZhj.setUpdateTime(new Date());
        // 更新数据
        int update = dcBillHeadZhjMapper.updateByPrimaryKey(dcBillHeadZhj);
        return update > 0 ? dcBillHeadZhjDtoMapper.toDto(dcBillHeadZhj) : null;
    }

    /**
     * 功能描述:批量删除
     *
     * @param sids
     * @return
     */
    @Transient
    public void delete(List<String> sids, UserInfoToken userInfo) {
        dcBillHeadZhjMapper.deleteBySids(sids);
    }

    /**
     * 功能描述:查询所有数据
     *
     * @param exportParam
     * @param userInfo
     * @return
     */
    public List<DcBillHeadZhjDto> selectAll(DcBillHeadZhjParam exportParam, UserInfoToken userInfo) {
        DcBillHeadZhj dcBillHeadZhj = dcBillHeadZhjDtoMapper.toPo(exportParam);
        // dcBillHeadZhj.setTradeCode(userInfo.getCompany());
        List<DcBillHeadZhjDto> dcBillHeadZhjDtos = new ArrayList<>();
        List<DcBillHeadZhj> dcBillHeadZhjs = dcBillHeadZhjMapper.getList(dcBillHeadZhj);
        if (CollectionUtils.isNotEmpty(dcBillHeadZhjs)) {
            dcBillHeadZhjDtos = dcBillHeadZhjs.stream().map(head -> {
                DcBillHeadZhjDto dto = dcBillHeadZhjDtoMapper.toDto(head);
                return dto;
            }).collect(Collectors.toList());
        }
        return dcBillHeadZhjDtos;
    }

    /**
     * @param status
     * @return
     */
    public List<StatusInfo> queryListStatus(String status) {
        List<StatusInfo> statusInfos = dcBillHeadZhjMapper.queryListStatus(status);

        StatusInfo addInfoOne = new StatusInfo();
        addInfoOne.setCode("XX");
        addInfoOne.setName("非终审通过");
        StatusInfo addInoTwo = new StatusInfo();
        addInoTwo.setCode("XY");
        addInoTwo.setName("非删单");
        statusInfos.add(addInfoOne);
        statusInfos.add(addInoTwo);
        return statusInfos;
    }

    public List<StatusInfo> queryEntryStatus(String status) {
        return dcBillHeadZhjMapper.queryEntryStatus(status);
    }


    public List<StatusInfo> querySelectStatus(String status) {
        return dcBillHeadZhjMapper.querySelectStatus(status);
    }


    public ResultObject getListNoByHeadId(String headId) {
        //根据headId获取表体有多少条数据
        int listNums = dcBillListZhjMapper.getListNoByHeadId(headId);
        if (listNums != 1) {
            return ResultObject.createInstance(false);
        }
        return ResultObject.createInstance(true, "查询成功", listNums);
    }


    public DcBillHeadZhj getDcBillHeadZhj(DcBillHeadZhjParam dcBillHeadZhjParam) {

        DcBillHeadZhj dcBillHeadZhj = dcBillHeadZhjDtoMapper.toPo(dcBillHeadZhjParam);
        /**
         * 获得 seq流水号 并在首位添加 Z
         */
        long index = dcBillHeadZhjMapper.getSequence();
        String s1 = 'z' + Long.toString(index);

        dcBillHeadZhj.setBillListNo(s1);
        // 生成sid
        dcBillHeadZhj.setSid(UUID.randomUUID().toString());

        // 获取加工单位数据
        ProcessUnitInfo processUnitInfo = dcBillHeadZhjMapper.getProcessUnitInfo(dcBillHeadZhj.getEmsNo());
        if (processUnitInfo != null) {
            dcBillHeadZhj.setReceiveCode(processUnitInfo.getReceive_code());
            dcBillHeadZhj.setReceiveCreditCode(processUnitInfo.getReceive_credit_code());
            dcBillHeadZhj.setReceiveName(processUnitInfo.getReceive_name());
        }
        // 获取 经营单位数据
        BusinessUnitInfo businessUnitInfo = dcBillHeadZhjMapper.getBusinessUnitInfo(dcBillHeadZhj.getEmsNo());
        if (businessUnitInfo != null) {
            dcBillHeadZhj.setTradeCode(businessUnitInfo.getTrade_code());
            dcBillHeadZhj.setTradeCreditCode(businessUnitInfo.getTrade_credit_code());
            dcBillHeadZhj.setTradeName(businessUnitInfo.getTrade_name());
        }
        // 获取 录入单位数据
        InputUnitInfo inputUnitInfo = dcBillHeadZhjMapper.getInputUnitInfo(dcBillHeadZhj.getEmsNo());
        if (inputUnitInfo != null) {
            dcBillHeadZhj.setInputCode(inputUnitInfo.getInput_code());
            dcBillHeadZhj.setInputCreditCode(inputUnitInfo.getInput_credit_code());
            dcBillHeadZhj.setInputName(inputUnitInfo.getInput_name());
        }
        // 设置进出口标志
        dcBillHeadZhj.setIEMark("I");

        return dcBillHeadZhj;
    }

    public ResultObject recovery(DcBillHeadZhjParam dcBillHeadZhjParam) throws ParseException {
        // 判断表头是否备份
        int headIndex = dcBillHeadZhjMapper.isBackup(dcBillHeadZhjParam.getBillListNo());
        // 判断表体是否备份
        int listIndex = dcBillHeadZhjMapper.isBackup(dcBillHeadZhjParam.getBillListNo());
        if (headIndex == 0 && listIndex == 0) {
            return ResultObject.createInstance(false, "当前清单，没有历史备份数据，不能恢复！");
        }
        // 插入记录表
        Recovery recovery = new Recovery();
        recovery.setBill_list_no(dcBillHeadZhjParam.getBillListNo());
        recovery.setEms_no(dcBillHeadZhjParam.getEmsNo());
        recovery.setTrade_code(dcBillHeadZhjParam.getTradeCode());
        recovery.setStatus("R0");
        recovery.setBusiness_type("BILL");
        recovery.setNote("删改恢复");
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        recovery.setAppr_date(dateFormat.parse(dateFormat.format(now)));

        int num = dcBillHeadZhjMapper.insertByRecovery(recovery);
        if (num != 1) {
            return ResultObject.createInstance(false, "插入记录表的时候发生错误");
        }
        /**
         * 删单申请（申报类型为3、6）
         * 按清单流水号删除T_DC_BILL_HEAD数据，然后从T_DC_BILL_HEAD_HIS恢复获取STATUS、declare_type更新至T_DC_BILL_HEAD
         */
        if (DECLARE_TYPE_THREE.equals(dcBillHeadZhjParam.getDeclareType()) || DECLARE_TYPE_SIX.equals(dcBillHeadZhjParam.getDeclareType())) {
            int deleteNum = dcBillHeadZhjMapper.deleteByBillListNo(dcBillHeadZhjParam.getBillListNo());
            if (deleteNum != 1) {
                return ResultObject.createInstance(false, "按清单流水号删除时发生错误");
            }
            int insertNum = dcBillHeadZhjMapper.insertByBillListNo(dcBillHeadZhjParam.getBillListNo());
            if (insertNum != 1) {
                return ResultObject.createInstance(false, "按清单流水号恢复数据时发生错误");
            }
        }
        return ResultObject.createInstance(true, "恢复成功");
    }

    public ResultObject beforeHandleSave(BeforeSaveParam beforeSaveParam) {
        /**判断企业内部编号是否重复(只有新增的时候和 编辑的时候未修改emsListNo)
         * 查询同一手(帐)册号下是否重复
         */
        if (beforeSaveParam.getOrdleEmsListNo() == null || !beforeSaveParam.getOrdleEmsListNo().equals(beforeSaveParam.getEmsListNo())) {
            int conditionOne = dcBillHeadZhjMapper.quertEmsListNoIsRepeat(beforeSaveParam.getEmsListNo(), beforeSaveParam.getEmsNo());
            if (conditionOne != 0) {
                return ResultObject.createInstance(false, "同一手(帐)册号下重复");
            }

            /**
             * 校验删除记录表(t_dc_bill_head_his)中pre_seq_no不为空的内部编号是否重复
             */
            int conditionTwo = dcBillHeadZhjMapper.queryDeleteTable(beforeSaveParam.getEmsListNo());
            if (conditionTwo != 0) {
                return ResultObject.createInstance(false, "历史表内部编号重复");
            }
            return ResultObject.createInstance(true);

        }
        // 若存在表体数据则修改表体币值栏位为142 人民币，征免方式 修改为1（照章征税）
        if (STATUS.equals(beforeSaveParam.getStatus())) {
            int listNoNum = dcBillListZhjMapper.getListNoByHeadId(beforeSaveParam.getHeadId());
            if (listNoNum > 0 && (TRADE_MODE_0644.equals(beforeSaveParam.getTradeMode())
                    || TRADE_MODE_0245.equals(beforeSaveParam.getTradeMode())
                    || TRADE_MODE_0844.equals(beforeSaveParam.getTradeMode())
                    || TRADE_MODE_0845.equals(beforeSaveParam.getTradeMode())
                   )) {
                int modifyNum = dcBillHeadZhjMapper.modifyCurrByHeadId(beforeSaveParam.getHeadId());
                // 如果查到的条数和更新的条数不一致的话
                if(modifyNum != listNoNum){
                    return ResultObject.createInstance(false, "查询条数和修改条数不匹配");
                }
            }
        }
        return ResultObject.createInstance(true, "保存前校验成功");
    }

    public ResultObject backupHeadAndList(DcBillHeadZhjParam dcBillHeadZhjParam) throws ParseException {
        // 判断表头是否备份
        int headIndex = dcBillListZhjMapper.isBackup(dcBillHeadZhjParam.getBillListNo());
        // 判断表体是否备份
        int listIndex = dcBillListZhjMapper.isBackup(dcBillHeadZhjParam.getBillListNo());
        // 已经备份过
        if(headIndex != 0 && listIndex != 0){
            return ResultObject.createInstance(true,"备份过数据则不用再备份");
        }
        if (headIndex == 0) {
            // 保存表头
            int index = dcBillHeadZhjMapper.backupHead(dcBillHeadZhjParam.getSid());
            if(index != 1){
                return ResultObject.createInstance(true,"表头保存时出现错误");
            }
        }
        if (listIndex == 0) {
             // 查询表体数据
            List<String> dcBillListZhj = dcBillListZhjMapper.ListNumById(dcBillHeadZhjParam.getSid());

            if (dcBillListZhj.size() > 0) {
                // 如果表体数量大于 0 保存表体数据
                int num = dcBillListZhjMapper.backupList(dcBillListZhj);
                if (num != dcBillListZhj.size()) {
                    return ResultObject.createInstance(true,"表体保存时出现错误");
                }
            }
        }
        // 修改DECLARE_TYPE=’3’,STATUS=’B1’  修改清单申报时间为当前时间，修改清单申报人为当前用户，修改申报单位信息[含信用代码和名称]
        dcBillHeadZhjParam.setDeclareType("3");
        dcBillHeadZhjParam.setStatus("B1");
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dcBillHeadZhjParam.setDeclareDate(dateFormat.parse(dateFormat.format(now)));
        // 更新数据
        int update = this.update(dcBillHeadZhjDtoMapper.toPo(dcBillHeadZhjParam));
        if(update != 1){
            return ResultObject.createInstance(true,"更新数据失败");
        }
        //向任务表T_DC_DEC_TASK表中插入任务
        Task task = new Task();
        task.setTradeCode(dcBillHeadZhjParam.getTradeCode());
        task.setBillListNo(dcBillHeadZhjParam.getBillListNo());
        task.setEmsNo(dcBillHeadZhjParam.getEmsNo());
        task.setDeclareChannel(dcBillHeadZhjParam.getDeclareChannel());
        task.setStatus("0");
        task.setSendRecvType("S");
        int insertNum = dcBillHeadZhjMapper.insertByTask(task);
        if (insertNum != 1) {
            return ResultObject.createInstance(false,"插入任务时发生错误");
        }

        return ResultObject.createInstance(true,"备份成功");
    }
}
